package handlers

import (
	"app-sys-man/cache"
	"app-sys-man/models"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	appname := c.PostForm("appname")
	title := c.PostForm("title")
	address := c.PostForm("address")

	if appname == "" || title == "" || address == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}

	data := models.App{
		AppName: appname,
		Title:   title,
		Address: address,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	redis_key := "app_" + strconv.Itoa(int(data.ID))
	var app models.App
	models.DB.Where("id=?", data.ID).First(&app)
	json.Marshal(app)
	cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func List(c *gin.Context) {
	var app []*models.App
	redis_key := "list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&app)

		jsonData, _ := json.Marshal(app)

		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &app)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": app,
	})
	return
}

func Select(c *gin.Context) {
	id := c.Query("id")

	var app models.App
	err := models.DB.Where("id=?", id).First(&app).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	redis_key := "app_select_" + id
	cache.Rdb.Get(cache.Ctx, redis_key).Int()
	json.Marshal(app)
	cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": app,
	})
	return
}
